package com.koron.car.web.costregister.controller;

import cn.hutool.core.date.DateTime;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.bean.base.Response;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.car.web.costregister.bean.entity.CostRegister;
import com.koron.car.web.costregister.bean.query.CostRegisterQuery;
import com.koron.car.web.costregister.bean.vo.CostRegisterExcel;
import com.koron.car.web.costregister.bean.vo.CostRegisterVO;
import com.koron.car.web.costregister.service.CostRegisterService;
import com.koron.common.core.annocation.CasUser;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.interceptor.OrderByInterceptor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * (CostRegister)表控制层
 *
 * @author twcao
 * @since 2022-03-14 12:27:26
 */
@Slf4j
@RestController
@RequestMapping("CostRegister")
@Api(tags = "车辆管理-费用录入")
public class CostRegisterController {

    @Autowired
    private CostRegisterService service;

    @GetMapping("/selectOne")
    @ApiOperation("根据记录id查询信息")
    @ApiImplicitParam(name = "id", value = "记录id", required = true)
    public Response<CostRegisterVO> selectOne(@RequestParam String id) {
        log.info("根据记录id查询信息， id = {}", id);
        CostRegisterVO bean = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), service, "queryById", CostRegisterVO.class, id);
        return Response.ok(bean);
    }

    @GetMapping("/queryList")
    @ApiOperation("根据条件查询列表")
    public Response<PageInfo<CostRegisterVO>> queryList(CostRegisterQuery query) {
        log.info("根据条件查询列表， query = {}", JSON.toJSONString(query));
        OrderByInterceptor.setOrderBy(query.getOrders());
        PageHelper.startPage(query.getPage(), query.getPageSize());
        List<CostRegisterVO> beans = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), service, "queryList", List.class, query);
        return Response.ok(new PageInfo<>(beans));
    }

    @PostMapping("/saveOrUpdate")
    @ApiOperation("创建/更新费用登记")
    public Response<CostRegisterVO> saveOrUpdate(@RequestBody CostRegisterVO cost) {
        log.info("创建/更新费用登记， cost = {}", JSON.toJSONString(cost));
        CostRegisterVO bean = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), service, StringUtils.isBlank(cost.getId()) ? "insert" : "update", CostRegisterVO.class, cost);
        return Response.ok(bean);
    }

    @GetMapping("/deleteById")
    @ApiOperation("根据id删除费用登记")
    @ApiImplicitParam(name = "id", value = "id", required = true)
    public Response<String> deleteById(@CasUser @ApiIgnore EamUser user, @RequestParam String id) {
        ADOConnection.runTask(user.getCurrDs(), service, "deleteById", Boolean.class, id);
        return Response.ok("删除成功", id);
    }

    @GetMapping("/deleteByIds")
    @ApiOperation("根据id批量删除费用登记")
    public Response<String> deleteByIds(@CasUser @ApiIgnore EamUser user, @RequestParam List<String> ids){
        ADOConnection.runTask(user.getCurrDs(), service, "deleteByIds", Boolean.class, ids);
        return Response.ok("删除成功!");
    }

    @PostMapping("/saveOrUpdateBatch")
    @ApiOperation("批量新增ETC费用")
    public Response<List<CostRegister>> saveBatch(@RequestBody List<CostRegister> costList, @RequestParam(required = false) Boolean submit) {
        log.info("批量新增ETC费用， costList size = {}", costList.size());
        List<CostRegister> result = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), service, (submit != null && submit) ? "updateBatch" : "saveBatch", List.class, costList);
        return Response.ok(result);
    }

    @PostMapping("/queryByIds")
    @ApiOperation("根据ids查询")
    public Response<List<CostRegister>> queryByIds(@RequestBody List<String> ids){
        log.info("根据ids查询， ids size = {}", ids.size());
        List<CostRegister> result = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), service,"queryByIds",List.class,ids);
        return Response.ok(result);
    }

    @PostMapping("/importOilCostExcel")
    @ApiOperation("导入加油费")
    public Response<String> importOilCostExcel(@RequestBody MultipartFile file) {
        try {
            ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), service, "importOilCostExcel", file);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Response.fail("加油费导入失败！");
        }
        return Response.ok("加油费导入成功！");
    }

    @PostMapping("/importRepairFeeCostExcel")
    @ApiOperation("导入维修费")
    public Response<String> importRepairFeeCostExcel(@RequestBody MultipartFile file) {
        try {
            ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), service, "importRepairFeeCostExcel", file);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Response.fail("维修费导入失败！");
        }
        return Response.ok("维修费导入成功！");
    }


    @GetMapping("/exportOilCostTemplate")
    @ApiOperation("加油费导出模板")
    public void exportTemplate(HttpServletResponse response) throws IOException {
        List<CostRegisterExcel> excels = new ArrayList<>();
        CostRegisterExcel costRegister1 = new CostRegisterExcel();
        costRegister1.setDriverName("张三");
        costRegister1.setLicPlateNum("粤XXXXX1");
        costRegister1.setStartTime(DateTime.now().toString("yyyy-MM-dd hh:mm:ss"));
        costRegister1.setOilNumber("95号汽油");
        costRegister1.setOil(45.74);
        costRegister1.setCost(435.9);
        costRegister1.setRemark("深圳中南深长加油站1");

        CostRegisterExcel costRegister2 = new CostRegisterExcel();
        costRegister2.setDriverName("李四");
        costRegister2.setLicPlateNum("粤XXXXX2");
        costRegister2.setStartTime(DateTime.now().toString("yyyy-MM-dd hh:mm:ss"));
        costRegister2.setOilNumber("92号汽油");
        costRegister2.setOil(45.74);
        costRegister2.setCost(435.9);
        costRegister2.setRemark("深圳中南深长加油站2");

        excels.add(costRegister1);
        excels.add(costRegister2);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("加油费用导入模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), CostRegisterExcel.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .sheet("加油费用导入模板")
                .doWrite(excels);
    }

    @GetMapping("/exportRepairFeeTemplate")
    @ApiOperation("维修费导出模板")
    public void exportRepairFeeTemplate(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("维修费用导入模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        BufferedInputStream inputStream = null;
        BufferedOutputStream outputStream = null;
        try {
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources("excelTemplate/repairFee.xlsx");
            Resource resource = resources[0];
            InputStream is = resource.getInputStream();
            inputStream = new BufferedInputStream(is);
            outputStream = new BufferedOutputStream(response.getOutputStream());
            byte[] bytes = new byte[2048];
            int len = -1;
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
        } catch (IOException e) {
            log.error("exportRepairFeeTemplate:{} ",e.getMessage());
            log.error(e.getMessage(), e);
        } finally {
            outputStream.close();
            inputStream.close();
        }
    }

}
